from flask import Blueprint, jsonify, request
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from libs.conn import execute, fetchone, system_log
import hashlib

login_bp = Blueprint('login', __name__)

# 登录视图
@login_bp.route('/api/login', methods=['POST'])
def login():
    username = request.json.get('username')
    password = request.json.get('password')
    user = fetchone("SELECT * FROM users WHERE username=?", (username,))
    if user and user['password'] == hashlib.sha256(password.encode()).hexdigest():
        access_token = create_access_token(identity=username)
        system_log(f"用户 {username} 登录成功")
        return { 'status': 'ok', 'data': access_token }
    else:
        system_log(f"用户 {username} 登录失败")
        return { 'status': 'error', 'data': '用户名或密码错误' }

@login_bp.route('/api/profile')
@jwt_required()
def profile():
    # 获取当前用户信息
    current_user = get_jwt_identity()  # 解码 Token 中的身份信息
    user_info = {
        'username': current_user
    }
    return { 'status': 'ok', 'data': user_info }

@login_bp.route('/api/modify_password', methods=['POST'])
@jwt_required()
def modify_password():
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    # 获取当前用户信息
    current_user = get_jwt_identity()  # 解码 Token 中的身份信息
    current_user = fetchone("SELECT * FROM users WHERE username=?", (current_user,))
    if current_user['password'] == hashlib.sha256(old_password.encode()).hexdigest():
        execute("UPDATE users SET password=? WHERE id=?", (hashlib.sha256(new_password.encode()).hexdigest(), current_user['id']))
        system_log(f"用户 {current_user['username']} 修改密码成功")
        return { 'status': 'ok', 'data': '密码修改成功' }
    else:
        system_log(f"用户 {current_user['username']} 修改密码失败，旧密码错误")
        return { 'status': 'error', 'data': '旧密码错误' }

# 登出视图
@login_bp.route('/api/logout', methods=['POST'])
@jwt_required()
def logout():
    current_user = get_jwt_identity()  # 解码 Token 中的身份信息
    system_log(f"用户 {current_user} 登出成功")
    return { 'status': 'ok', 'data': '登出成功' }

@login_bp.route('/api/refresh_token', methods=['POST'])
@jwt_required()
def refresh_token():
    current_user = get_jwt_identity()  # 解码 Token 中的身份信息
    access_token = create_access_token(identity=current_user)
    return { 'status': 'ok', 'data': access_token }


